<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :loading="loading"
    :helpMessage="t('modal.helpMessage')"
    width="800px"
    :minHeight="420"
    :title="getTitle"
    @ok="handleSubmit"
    :okText="t('modal.confirm')"
    :cancelText="t('modal.cancel')"
  >
    <a-form ref="formRef" :model="formData" auto-label-width>
      <a-form-item
        field="type"
        :label="t('modal.addFrom.rule_type')"
        style="margin-bottom: 15px"
      >
        <a-radio-group
          type="button"
          v-model="formData.rule_type"
          @change="handleChangeType"
        >
          <a-radio :value="1">{{ $t('modal.addFrom.directory') }}</a-radio>
          <a-radio :value="2">{{ $t('modal.addFrom.menu') }}</a-radio>
          <a-radio :value="3">{{ $t('modal.addFrom.button') }}</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item
            field="title"
            :label="t('searchTable.columns.title')"
            validate-trigger="input"
            :rules="[
              { required: true, message: t('modal.please.write.title') },
            ]"
            style="margin-bottom: 15px"
          >
            <a-input
              v-model="formData.title"
              :placeholder="t('modal.please.write.title')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="locale"
            :label="t('searchTable.columns.locale')"
            validate-trigger="input"
            style="margin-bottom: 15px"
          >
            <a-input
              v-model="formData.locale"
              :placeholder="t('modal.please.write.locale')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            :label="t('modal.addFrom.parent_menu')"
            field="pid"
            style="margin-bottom: 15px"
          >
            <a-tree-select
              :placeholder="t('modal.please.write.parent_menu')"
              :data="parntList"
              :fieldNames="{
                key: 'id',
                title: 'locale',
                children: 'children',
              }"
              v-model="formData.pid"
            >
            </a-tree-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            :label="t('modal.addFrom.weight')"
            field="weight"
            style="margin-bottom: 15px"
          >
            <a-input-number
              v-model="formData.weight"
              :placeholder="t('modal.please.write.weight')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.rule_type != 3">
          <a-form-item
            :label="t('searchTable.columns.icon')"
            field="icon"
            style="margin-bottom: 15px"
          >
            <a-input-search
              v-model="formData.icon"
              :placeholder="t('modal.please.write.icon')"
              search-button
            >
              <template v-if="formData.icon" #prefix>
                <Icon :icon="formData.icon" :size="23"></Icon>
              </template>
              <template #button-icon>
                <a-popover position="bl" trigger="click">
                  <icon-apps />
                  <template #content>
                    <IconPicker
                      @change="
                        (icon) => {
                          formData.icon = icon;
                        }
                      "
                    ></IconPicker>
                  </template>
                </a-popover>
              </template>
            </a-input-search>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.rule_type != 3">
          <a-form-item
            field="route_path"
            :label="t('modal.addFrom.route_path')"
            validate-trigger="input"
            :rules="[
              { required: true, message: t('modal.please.write.route_path') },
            ]"
            style="margin-bottom: 15px"
          >
            <a-input
              v-model="formData.route_path"
              :placeholder="t('modal.please.write.route_path')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.rule_type != 3">
          <a-form-item
            field="route_name"
            :label="t('modal.addFrom.route_name')"
            validate-trigger="input"
            :rules="[
              { required: true, message: t('modal.please.write.route_name') },
            ]"
            style="margin-bottom: 15px"
          >
            <a-input
              v-model="formData.route_name"
              :placeholder="t('modal.please.write.route_name')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.rule_type == 1">
          <a-form-item
            field="redirect"
            :label="t('modal.addFrom.redirect')"
            validate-trigger="input"
            :rules="[
              { required: true, message: t('modal.please.write.redirect') },
            ]"
          >
            <a-input
              v-model="formData.redirect"
              :placeholder="t('modal.please.write.redirect')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.rule_type == 2">
          <a-form-item
            field="component"
            :label="t('modal.addFrom.component')"
            validate-trigger="input"
            :rules="[
              { required: true, message: t('modal.please.write.component') },
            ]"
          >
            <a-input
              v-model="formData.component"
              :placeholder="t('modal.please.write.component')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.rule_type == 3">
          <a-form-item
            field="permission"
            :label="t('modal.addFrom.permission')"
            validate-trigger="input"
            :rules="[
              { required: true, message: t('modal.please.write.permission') },
            ]"
          >
            <a-input
              v-model="formData.permission"
              :placeholder="t('modal.please.write.permission')"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.rule_type != 3">
          <a-form-item
            field="is_iframe"
            :label="t('modal.addFrom.is_iframe')"
            style="margin-bottom: 5px"
          >
            <a-radio-group v-model="formData.is_iframe" :options="OYoptions" />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.rule_type != 3">
          <a-form-item
            field="keepalive"
            :label="t('modal.addFrom.keepalive')"
            style="margin-bottom: 5px"
          >
            <a-radio-group v-model="formData.keepalive" :options="OYoptions" />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.rule_type != 3">
          <a-form-item
            field="hide_in_menu"
            :label="t('modal.addFrom.hide_in_menu')"
            style="margin-bottom: 5px"
          >
            <a-radio-group
              v-model="formData.hide_in_menu"
              :options="OYoptions"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.rule_type != 3">
          <a-form-item
            field="hide_children_in_menu"
            :label="t('modal.addFrom.hide_children_in_menu')"
            style="margin-bottom: 5px"
          >
            <a-radio-group
              v-model="formData.hide_children_in_menu"
              :options="OYoptions"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.rule_type != 3">
          <a-form-item
            field="no_affix"
            :label="t('modal.addFrom.no_affix')"
            style="margin-bottom: 5px"
          >
            <a-radio-group v-model="formData.no_affix" :options="OYoptions" />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.rule_type != 3">
          <a-form-item
            field="active_menu"
            :label="t('modal.addFrom.active_menu')"
            style="margin-bottom: 5px"
          >
            <a-radio-group
              v-model="formData.active_menu"
              :options="OYoptions"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.rule_type != 3">
          <a-form-item
            field="requires_auth"
            :label="t('modal.addFrom.requires_auth')"
            style="margin-bottom: 5px"
          >
            <a-radio-group
              v-model="formData.requires_auth"
              :options="OYoptions"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="is_default"
            :label="t('modal.addFrom.is_default')"
            style="margin-bottom: 5px"
          >
            <a-radio-group v-model="formData.default" :options="OYoptions" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import useLoading from '@/hooks/loading';
  import { useI18n } from 'vue-i18n';
  import { cloneDeep } from 'lodash-es';
  //api
  import { IconPicker, Icon } from '@/components/Icon';
  import { Message } from '@arco-design/web-vue';
  import {
    DataTreeItemRule,
    getAllRule,
    add,
    update,
  } from '@/api/systemManage/rule';

  export default defineComponent({
    name: 'AddBook',
    components: { BasicModal, IconPicker, Icon },
    emits: ['success'],
    setup(_, { emit }) {
      const { t } = useI18n();
      const isUpdate = ref(false);
      const parntList = ref<DataTreeItemRule[]>([]);
      //表单
      const formRef = ref<FormInstance>();
      //表单字段
      const basedata = {
        id: 0,
        title: '',
        locale: '',
        weight: 1,
        rule_type: 1, // 1目录 2菜单 3按钮
        pid: 0,
        icon: '',
        route_path: '', //path
        route_name: '', //name
        component: '', //外部layar、import
        redirect: '', //重定向
        permission: '', //页面内权限 roles
        is_iframe: false, //是否外链
        keepalive: false, //是否缓存 0=否1=是
        requires_auth: false, //是否需要登录鉴权 默认false
        hide_in_menu: false, //是否在左侧菜单中隐藏该项
        hide_children_in_menu: false, //强制在左侧菜单中显示单项
        active_menu: false, //高亮设置的菜单项
        no_affix: false, //如果设置为true，标签将不会添加到tab-bar中
        default: false, //如果设置为true，标签将不会添加到tab-bar中
      };
      const formData = ref(basedata);
      const m_component = ref('');

      function mapRuleToTreeItem(list: any[]): DataTreeItemRule[] {
        return list.map((item) => ({
          id: item.id,
          title: item.title,
          locale: t(item.locale),
          children: item.children ? mapRuleToTreeItem(item.children) : [],
        }));
      }

      const [registerModal, { setModalProps, closeModal }] = useModalInner(
        async (data) => {
          formRef.value?.resetFields();
          setModalProps({ confirmLoading: false });
          isUpdate.value = !!data?.isUpdate;
          const resultdata = await getAllRule({
            state: 2,
            rule_type: unref(isUpdate)
              ? data.record.rule_type
              : formData.value.rule_type,
          });
          const parntList_df: any = [
            { id: 0, title: '', pid: 0, locale: '一级菜单' },
          ];
          if (resultdata) {
            parntList.value = parntList_df.concat(
              mapRuleToTreeItem(resultdata.list)
            );
          } else {
            parntList.value = parntList_df;
          }
          if (unref(isUpdate)) {
            m_component.value = data.record.component;
            formData.value = cloneDeep(data.record);
          } else {
            m_component.value = '';
            formData.value = cloneDeep(basedata);
          }
        }
      );
      const getTitle = computed(() =>
        !unref(isUpdate) ? t('modal.add') : t('modal.edit')
      );
      //点击确认
      const { loading, setLoading } = useLoading();
      const handleSubmit = async () => {
        try {
          const res = await formRef.value?.validate();
          if (!res) {
            setLoading(true);
            if (
              formData.value.rule_type == 0 &&
              formData.value.component == ''
            ) {
              formData.value.component = 'LAYOUT';
            }
            if (
              formData.value.rule_type == 0 &&
              formData.value.route_path &&
              formData.value.route_path.substr(0, 1) != '/'
            ) {
              formData.value.route_path = '/' + formData.value.route_path;
            }

            if (isUpdate.value) {
              Message.loading({
                content: t('searchTable.message.loading.updating'),
                id: 'upStatus',
              });
              let params = {
                title: formData.value.title,
                locale: formData.value.locale,
                parent_id: formData.value.pid,
                weight: formData.value.weight,
                rule_type: formData.value.rule_type,
                icon: formData.value.icon,
                route_name: formData.value.route_name,
                route_path: formData.value.route_path,
                component: formData.value.component,
                redirect: formData.value.redirect,
                permission: formData.value.permission,
                is_iframe: formData.value.is_iframe,
                keepalive: formData.value.keepalive,
                requires_auth: formData.value.requires_auth,
                hide_in_menu: formData.value.hide_in_menu,
                hide_children_in_menu: formData.value.hide_children_in_menu,
                active_menu: formData.value.active_menu,
                no_affix: formData.value.no_affix,
                default: formData.value.default,
                id: formData.value.id,
              };
              await update(params);
              Message.success({
                content: t('searchTable.message.loading.update.successful'),
                id: 'upStatus',
              });
            } else {
              Message.loading({
                content: t('searchTable.message.loading.adding'),
                id: 'upStatus',
              });
              let params = {
                title: formData.value.title,
                locale: formData.value.locale,
                parent_id: formData.value.pid,
                weight: formData.value.weight,
                rule_type: formData.value.rule_type,
                icon: formData.value.icon,
                route_name: formData.value.route_name,
                route_path: formData.value.route_path,
                component: formData.value.component,
                redirect: formData.value.redirect,
                permission: formData.value.permission,
                is_iframe: formData.value.is_iframe,
                keepalive: formData.value.keepalive,
                requires_auth: formData.value.requires_auth,
                hide_in_menu: formData.value.hide_in_menu,
                hide_children_in_menu: formData.value.hide_children_in_menu,
                active_menu: formData.value.active_menu,
                no_affix: formData.value.no_affix,
                default: formData.value.default,
              };
              await add(params);
              Message.success({
                content: t('searchTable.message.loading.add.successful'),
                id: 'upStatus',
              });
            }
            closeModal();
            emit('success');
            setLoading(false);
          }
        } catch (error) {
          setLoading(false);
          Message.clear('top');
        }
      };
      //切换菜单类型
      const handleChangeType = (value: any) => {
        if (value == 1) {
          formData.value.component = 'LAYOUT';
        } else if (value == 2) {
          formData.value.component = m_component.value;
          formData.value.redirect = '';
        } else if (value == 3) {
          formData.value.component = '';
          formData.value.redirect = '';
        }
      };
      const OYoptions = computed(() => [
        {
          label: t('searchTable.columns.defaultState.default'),
          value: false,
        },
        {
          label: t('searchTable.columns.defaultState.no_default'),
          value: true,
        },
      ]);
      return {
        registerModal,
        getTitle,
        handleSubmit,
        formRef,
        loading,
        formData,
        parntList,
        t,
        OYoptions,
        handleChangeType,
      };
    },
  });
</script>
